<template>
    <el-row class="info-row">
        <el-tabs :tab-position="tabPosition" style="min-height: 400px;">
            <el-tab-pane label="基本设置">
                <div class="detai-row">
                    <div class="tab-title">
                        <h2>基本设置</h2>
                    </div>
                    <el-row>

                        <el-col :span="12" :md="20" :sm="22" :xs="22">
                            <el-form :model="userInfo" label-width="120px" :rules="editFormRules" ref="userInfo">
                                <el-form-item label="头像" prop="avatar">
                                    <el-col :lg="12" :md="16" :sm="22" :xs="22">
                                        <el-row>
                                                <div style="align-items: center ;padding: 0 0 0 10px">
                                                    <!-- :before-upload="beforeUpload" -->
                                                    <!-- action="https://jsonplaceholder.typicode.com/posts/"  -->
                                                    <el-upload
                                                        v-model="userInfo.avatar"
                                                        :http-request="Upload"
                                                        :multiple="false"
                                                        :show-file-list="false"
                                                        action="uploadUrl"
                                                        list-type="picture">
                                                        <div class="avator-img">
                                                            <img :src="userInfo.avatar"/>
                                                        </div>
                                                        <div slot="tip" class="el-upload__tip">点击图片上传：只支持jpg/png文件，且不超过500kb</div>
                                                    </el-upload>
                                                </div>
                                        </el-row>
                                    </el-col>
                                </el-form-item>

                                <el-form-item label="登录名" prop="name">
                                    <el-col :lg="12" :md="16" :sm="22" :xs="22">
                                        <el-input v-model="userInfo.name"/>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="性别">
                                    <el-radio-group v-model="userInfo.sex" size="small">
                                        <el-radio-button label="1">男</el-radio-button>
                                        <el-radio-button label="0">女</el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                                <el-form-item label="花名">
                                    <el-col :lg="8" :md="12" :sm="16" :xs="20">
                                        <el-input v-model="userInfo.nickname"></el-input>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="邮箱">
                                    <el-col :lg="8" :md="12" :sm="16" :xs="20">
                                        <el-input v-model="userInfo.email"></el-input>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="电话" prop="telephone">
                                    <el-col :lg="8" :md="12" :sm="16" :xs="20">
                                        <el-input v-model="userInfo.telephone"></el-input>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="生日">
                                    <el-col :lg="8" :md="12" :sm="16" :xs="20">
                                        <el-date-picker type="date" placeholder="选择日期"
                                                        v-model="userInfo.birthday"></el-date-picker>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="地址">
                                    <el-col :lg="8" :md="12" :sm="16" :xs="20">
                                        <el-input type="textarea" v-model="userInfo.address"></el-input>
                                    </el-col>
                                </el-form-item>
                                <el-form-item label="最后登陆时间">
                                    <el-col :lg="8" :md="12" :sm="16" :xs="20">
                                        <el-input  :disabled=true type="label" v-model="userInfo.lastLoginTime" :formatter="formatDate"></el-input>
                                    </el-col>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>
                    <div slot="footer" class="form-footer">
                        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">更新个人信息</el-button>
                    </div>
                </div>
            </el-tab-pane>
            <el-tab-pane label="安全设置">
                <div class="tab-title">
                    <h2>安全设置</h2>
                </div>
            </el-tab-pane>
            <el-tab-pane label="账户关联">
                <div class="tab-title">
                    <h2>账户关联</h2>
                </div>
            </el-tab-pane>
            <el-tab-pane label="消息通知">
                <div class="tab-title">
                    <h2>消息通知</h2>
                </div>
            </el-tab-pane>
        </el-tabs>
    </el-row>
</template>

<script>
    import util from '../../common/utils'
    import {client}  from '../../store/oss'
    import {getCurrentUser,editUser,getAliToken} from '../../api/system/user';
    import {getTime} from '../../api/commonUtil';

    export default {
        name: "UserInfo",
        data() {
            let checkPhone = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入电话号码！'));
                } else if (!util.isvalidPhone(value)) {
                    callback(new Error('请输入正确的11位手机号码'));
                } else {
                    callback()
                }
            };
            let checkEMail = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入邮箱地址！'));
                } else if (!util.isvalidEmail(value)) {
                    callback(new Error('请输入正确邮箱地址'));
                } else {
                    callback()
                }
            };
            let checkName = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('用户名不能为空'));
                }
                setTimeout(() => {
                    if (value.length < 3 || value.length > 13) {
                        callback(new Error('用户名长度3-12'));
                    } else {
                        callback();
                    }
                }, 1000);
            };
            return {
                tempUrl: '', //存上传后的图片url
                dataObj: {}, //存签名信息
                baseAli: 'oss-cn-beijing.aliyuncs.com', //后面连接图片url用的，根据自己aili OSS 配制修改
                progress:0 ,//进度条
                tabPosition: 'left',
                editLoading: false,
                ossName:"",
                uploadUrl:"",
                //编辑界面数据
                userInfo: {
                    name: '',
                    sex: '1',
                    nickname: '',
                    email: '',
                    birthday: '',
                    address: '',
                    avatar:'',
                    lastLoginTime:''
                },
                avatar: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
                editFormRules: {
                    name: [
                        {validator: checkName, required: true, trigger: 'blur'},
                    ],
                    telephone: [
                        {validator: checkPhone, required: true, trigger: 'blur'}
                    ],
                    email: [
                        {validator: checkEMail, required: true, trigger: 'blur'}
                    ]
                },
            }
        }, methods: {
            beforeUpload() {
                return new Promise((resolve, reject) => {
                    //从后台获取第一步所需的数据
                    getAliToken().then(response => {
                        this.dataObj = response.data;
                        this.ossName = response.data;
                        resolve(true)
                    }).catch(err => {
                        console.error(err);
                        reject(false)
                    })
                })
            },
            Upload(file) {
                const that = this;
                //判断扩展名
                const tmpcnt = file.file.name.lastIndexOf(".")
                const exname = file.file.name.substring(tmpcnt + 1)
                const names = ['jpg', 'jpeg', 'webp', 'png','bmp']
                if(names.indexOf(exname)< 0 ){
                    this.$message.error("不支持的格式!")
                    return
                }
                async function multipartUpload () {
                    const fileName = that.ossName + file.file.uid+"."+exname
                    //定义唯一的文件名，打印出来的uid其实就是时间戳
                    //client 是第一步中的 client
                    client().multipartUpload(fileName, file.file,{
                            //获取进度条的值
                            /*progress:function (p) {
                                console.log(p)
                                that.progress = p*100
                            },*/
                        }).then(result => {
                            console.log(result)
                            //下面是如果对返回结果再进行处理，根据项目需要
                            that.userInfo.avatar = 'https://'+result.bucket+'.'+that.baseAli+ '/' + result.name;
                        }).catch(err => {
                        console.log("err:",err)
                    })
                }
                multipartUpload ()
            },
            formatDate: function (row, column, cellValue, index) {
                return undefined ===cellValue ? 'null' : getTime(cellValue);
            },
            //编辑
            editSubmit: function () {
                this.$refs.userInfo.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let updateUser = Object.assign({}, this.userInfo);
                            updateUser.birthday = (!updateUser.birthday || updateUser.birthday == '') ? '' : util.formatDate.format(new Date(updateUser.birthday), 'yyyy-MM-dd');
                            editUser(updateUser).then((res) => {
                                this.editLoading = false;
                                if (res.status) {
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    localStorage.setItem('ms_avatar',updateUser.avatar);
                                    setTimeout(function(){ location.reload(); }, 1000);
                                } else {
                                    this.$message({
                                        message: '提交失败',
                                        type: 'error'
                                    });
                                }
                                this.getUserInfo();
                            });

                        });
                    }
                });
            },
            getUserInfo: function () {
                getCurrentUser().then((res)=>{
                    this.editLoading = false;
                    if (res.status) {
                        this.$message({
                            message: '查询成功',
                            type: 'success'
                        });
                        this.userInfo=res.data
                    } else {
                        this.$message({
                            message: '提交失败',
                            type: 'error'
                        });
                    }
                });
            }
        },
        mounted() {
            this.getUserInfo();
        }
    }
</script>

<style scoped>

    .tab-title {
        padding: 0 0 4px 12px
    }

    .avator-img img{
        display: block;
        width: 100px;
        height: 100px;
        border-radius: 50%;
    }
    .form-footer {
        padding-left: 20px;
    }
</style>
